import { queryDoclist, addDoc, queryDocDetail, updateDoc, deleteDoc } from '@/services/doc';
import { uploadImg } from '@/services/api';
import { message } from 'antd';
import router from 'umi/router';
export default {
  namespace: 'doc',

  state: {
    data: {
      list: [],
      pagination: {},
    },
    docDetail: {},
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryDoclist, payload);
      if (response.status === 'success') {
        yield put({
          type: 'save',
          payload: {
            list: response.data.data,
            pagination: {
              total: response.data.total,
              pageSize: 10,
              current: parseInt(response.data.current_page, 10) || 1,
            },
          },
        });
      }
    },
    *addDoc({ payload }, { call, put }) {
      const response = yield call(addDoc, payload);
      if (response.status === 'success') {
        message.success('提交成功');
        router.push('/doclist/table-list');
      } else {
        message.error('提交失败');
      }
    },
    *fetchDetail({ payload, callback }, { call, put }) {
      const response = yield call(queryDocDetail, payload);
      yield put({
        type: 'saveDetail',
        payload: response.data,
      });
      if (callback) callback();
    },
    *fetchUpdateDetail({ payload }, { call, put }) {
      const response = yield call(updateDoc, payload);
      if (response.status === 'success') {
        message.success('更新成功');
        router.push('/doclist/table-list');
      } else {
        message.error('更新失败');
      }
    },
    *fetchDelDoc({ payload, callback }, { call, put }) {
      const response = yield call(deleteDoc, payload);
      if (callback) callback();
    },
    *fetchUploadImg({ payload, callback }, { call, put }) {
      const response = yield call(uploadImg, payload);
      if (callback) callback(response.data);
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    saveDetail(state, action) {
      return {
        ...state,
        docDetail: action.payload,
      };
    },
  },
};
